<template>
  <div class="content-main">
    <item-list class="sort-list" :idx="sort"
    :items="sortCover" @changeIdx="changeSort"></item-list>

    <article-list :articles="article.abstracts" class="article-list"
    @fetchArticleAbstracts="fetchArticleAbstracts"></article-list>
  </div>
</template>

<script>
import ItemList from '@/components/utils/ItemList.vue'
import ArticleList from '@/components/ArticleList.vue';

  export default {
    components: {
      ItemList,
      ArticleList
    },
    data() {
      return {
        sortCover: ['推荐', '最热', '最新'],
        articleRestrictionAbstractsMap: new Map()
      }
    },
    computed: {
      sort() {
        return parseInt(this.$route.query.s) || 0;
      },
      type() {
        let types = ['all', '数理', '语言', '开发', '算法', '其他'];
        let idx = parseInt(this.$route.query.t) || 0;
        return types[idx];
      },
      articleRestriction() {
        let obj = {
          sort: this.sort
        }
        let type = this.type;
        if(type !== 'all') obj.type = type;
        return obj;
      },
      article() {
        let map = this.articleRestrictionAbstractsMap;
        if(!map.has(JSON.stringify(this.articleRestriction))) map.set(JSON.stringify(this.articleRestriction), {page: 0, abstracts: []});
        let item = map.get(JSON.stringify(this.articleRestriction));
        return item;
      }
    },
    watch: {
      articleRestriction() {
        this.fetchArticleAbstracts();
      }
    },
    methods: {
      changeSort(sort) {
        this.$router.push({
          path: this.$route.path,
          query: {
            ...this.$route.query,
            s: sort
          }
        })
      },
      fetchArticleAbstracts() {
        let restriction = this.articleRestriction;
        let item = this.article;
        this.$fetch({
          name: 'article abstracts',
          url: 'article',
          method: 'POST',
          data: {
            page: ++item.page,
            ...restriction
          }
        }).then(res => {
          if(res.data.success) {
            if(res.data.object.length) item.abstracts = item.abstracts.concat(res.data.object);
            else item.page--;
          } else {
            this.$alert({
              type: 'error',
              content: '获取文章内容失败'
            });
            item.page--;
          }
        }).catch(error => {
          this.$alert({
            type: 'error',
            content: '获取文章内容失败'
          });
          item.page--;
        })
      },
    },
  }
</script>

<style lang="less" scoped>
@w: var(--innerWidthPart1);

  .content-main {
    width: @w;
    background-color: white;

    .sort-list {
      --itemListWidth: calc(@w * 0.6);
      --itemListHeight: 50px;
    }

    .article-list {
      --articleListWidth: @w;
    }
  }


</style>